﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Senparc.Weixin.Open;
using Senparc.Weixin.Open.MessageHandlers;
using System.IO;
using Colorful.WeiXin.Utilities;
using Senparc.Weixin.Open.Entities.Request;
using MongoDB.Driver;
using Colorful.Database;

namespace Colorful.WeiXin.ThirdPartyMessageHandlers
{
    public class CustomThirdPartyMessageHandler : ThirdPartyMessageHandler
    {
        private string _appId;
        public CustomThirdPartyMessageHandler(Stream inputStream, PostModel encryptPostModel)
            : base(inputStream, encryptPostModel)
        {
            _appId = encryptPostModel.AppId;
        }

        public override string OnComponentVerifyTicketRequest(RequestMessageComponentVerifyTicket requestMessage)
        {
            using (var db = DbHelper.GetDb())
            {
                var id = db.WeChatSettings.Where(a => a.Id == _appId).Select(b => b.Id).FirstOrDefault();
                if (id == null)
                {
                    var wxSettting = new Models.WeChatSetting()
                    {
                        Id = _appId,
                        Ticket = requestMessage.ComponentVerifyTicket,
                        LastUpdate = DateTime.Now
                    };
                    db.WeChatSettings.Add(wxSettting);
                }
                else
                {
                    db.WeChatSettings.Update(a => a.Id == id, b => b.Ticket, requestMessage.ComponentVerifyTicket, b => b.LastUpdate, DateTime.Now);
                }
            }
            //var openTicketPath = Server.GetMapPath("~/App_Data/OpenTicket");
            //if (!Directory.Exists(openTicketPath))
            //{
            //    Directory.CreateDirectory(openTicketPath);
            //}

            ////RequestDocument.Save(Path.Combine(openTicketPath, string.Format("{0}_Doc.txt", DateTime.Now.Ticks)));

            ////记录ComponentVerifyTicket（也可以存入数据库或其他可以持久化的地方）
            //using (FileStream fs = new FileStream(Path.Combine(openTicketPath, string.Format("{0}.txt", RequestMessage.AppId)),FileMode.OpenOrCreate,FileAccess.ReadWrite))
            //{
            //    using (TextWriter tw = new StreamWriter(fs))
            //    {
            //        tw.Write(requestMessage.ComponentVerifyTicket);
            //        tw.Flush();
            //        //tw.Close();
            //    }
            //}
            return base.OnComponentVerifyTicketRequest(requestMessage);
        }

        public override string OnUnauthorizedRequest(RequestMessageUnauthorized requestMessage)
        {
            //取消授权
            return base.OnUnauthorizedRequest(requestMessage);
        }
    }
}
